#include "StaticMeshComponent.h"
#include "Scene/Scene.h"



void RStaticMeshComponent::SetStaticMesh(TSharedObjectPtr<RStaticMesh> InMesh)
{
    Mesh=InMesh;
    Materials=Mesh->DefaultMaterials;
}

void RStaticMeshComponent::SetMaterials(TVector<TSharedObjectPtr<RMaterial>> InMaterials)
{
    assert(Mesh&& "Must set mesh before set materials");
    Materials=InMaterials;
    assert(Materials.Num()==Mesh->GetSectionNum());
}

void RStaticMeshComponent::SetMaterial(TSharedObjectPtr<RMaterial> InMaterial,int32_t InSectionIndex)
{
    assert(Mesh&& "Must set mesh before set materials");
    assert(InSectionIndex<Mesh->GetSectionNum()&& "Mesh section index out of range");

    Materials[InSectionIndex]=InMaterial;
}

void RStaticMeshComponent::Paint(CRenderScene* InRenderData)
{
    Super::Paint(InRenderData);

    if(Hidden || !Mesh)
    {
        return;
    }

    SRenderMeshInstanceData& MeshInstanceData=InRenderData->MeshInstances.Emplace();
    MeshInstanceData.Position=GetNode()->GetWorldPosition();
    MeshInstanceData.Rotation=GetNode()->GetWorldRotation();
    MeshInstanceData.Scale=GetNode()->GetScale();

    MeshInstanceData.BoundingSphereRadius=Mesh->GetBoundingSphereRadius()*GetNode()->GetScale().GetMax();
    MeshInstanceData.CastShadow=bCastShadow;

    MeshInstanceData.MeshSections=Mesh->GetRenderMeshes();

    for(int64_t i=0;i<Mesh->GetSectionNum();i++)
    {
        TSharedObjectPtr<RMaterial> Material;
        if(Materials.Num()>i)
        {
            Material=Materials[i];
        }
        
        if(!Material)
        {
            Material=Mesh->DefaultMaterials[i];
        }
        assert(Material&& "Material must be valid");

        //Material->SyncToRenderThread();
        MeshInstanceData.Materials.Add(Material->GetRenderMaterial());
    }
  
    
}



SMatrix4x4 RStaticMeshComponent::GetWorldTransform()
{
    return GetNode()->GetWorldTransform();
}